package com.cloud.mall.consume.service.impl;

import com.cloud.mall.consume.domain.ErrorLog;
import com.cloud.mall.consume.service.ErrorService;
import com.cloud.mall.consume.wechat.common.MessageTemplate;
import com.cloud.mall.consume.wechat.common.Result;
import com.cloud.mall.consume.wechat.config.WechatConf;
import com.cloud.mall.log.mapper.SenderContactsMapper;
import com.cloud.mall.log.model.SenderContacts;
import com.cloud.mall.log.model.SenderContactsExample;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.client.RestTemplate;

import java.text.SimpleDateFormat;
import java.util.List;

@Slf4j
public abstract class AbstractErrorService  implements ErrorService {

    protected abstract SenderContactsMapper getSenderContactsMapper();
    protected abstract RestTemplate getRestTemplate();
    protected abstract WechatConf getWechatConf();

    @Override
    public void  sendMessage(ErrorLog errorLog){
        saveError(errorLog);
        //调用微信模板推送，可以对接短信或邮件
        List<SenderContacts> senderContacts = getSenderContactsMapper().selectByExample(new SenderContactsExample());
        for(SenderContacts contacts:senderContacts){
            sendWechatMessage(contacts.getOpenid(),errorLog);
        }
    }
    protected abstract  void saveError(ErrorLog errorLog);

    protected  void sendWechatMessage(String openid,ErrorLog errorLog){
        MessageTemplate messageTemplate = new MessageTemplate();
        // 设置模板id
        messageTemplate.setTemplateId("edmB_I0FK13P8Qnv1PhAb9nwfidCO1nmcukK26yTxI0");
        // 设置接收用户openId
        messageTemplate.setToUser(openid);
        //点击详情跳转的地址
        // messageTemplate.setUrl("http://www.baidu.com");
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //设置模板dada参数
        messageTemplate.getData().put("first", MessageTemplate.initData("测试", ""));
        messageTemplate.getData().put("keyword1", MessageTemplate.initData(errorLog.getClassName(), "#0000EE"));
        messageTemplate.getData().put("keyword2", MessageTemplate.initData(errorLog.getMethodName(), "#00CD00"));
        messageTemplate.getData().put("keyword3", MessageTemplate.initData(errorLog.getParamterContent(), ""));
        messageTemplate.getData().put("keyword4", MessageTemplate.initData(errorLog.getErrorContent(), ""));
        messageTemplate.getData().put("keyword5", MessageTemplate.initData(errorLog.getLineNumber()+"", ""));
        messageTemplate.getData().put("keyword6", MessageTemplate.initData(simpleDateFormat.format(errorLog.getCreateTime())+"\n", ""));
        messageTemplate.getData().put("keyword7", MessageTemplate.initData(errorLog.getIpaddr(), ""));
        log.info("{}",messageTemplate.toString());
        //调用微信接口，发送模板消息
        Result result = getRestTemplate().postForObject(String.format(WechatConf.PUSH_MESSAGE_URL, getWechatConf().getAccessToken()),
                messageTemplate, Result.class);
    }

}
